<?php
namespace app\index\controller;
use app\model\Sk as SkModel;

use think\Db;


class Sk extends Base
{   
    // 列表
    public function index(){
        $ulogin = $this->login_user;
        $map_params = [
           
        ];
        $map = getSearchParam($map_params);

        $map[] = ['utype','=',$ulogin['utype']];
        if ($ulogin['utype'] == 1) {
            $map[] = ['ram_id','=',$ulogin['ram_id']];
        }else{
            $map[] = ['user_id','=',$ulogin['user_id']];
        }
        
        $model = new SkModel();

        $list = $model->where($map)->order('id','desc')->select()->toarray();
        foreach ($list as $k => $vo) {
       
        }

        return apiResult('2000','获取成功',$list);
    }

    // 新增
    public function save(){
        $ulogin = $this->login_user;

        $param = file_get_contents('php://input');
        $param = json_decode($param,true);

        $fields = [
            'must'=>['name'],
            'nomust'=>['description']
        ];
        $save_data = paramFilter($param,$fields);
        if (!empty($save_data['error_msg'])) {
            return apiResult('5000',$save_data['error_msg']);
        }

        $model = new SkModel();
        // 启动事务 
        Db::startTrans();
        try{
            $save_data['utype'] = $ulogin['utype'];
            $save_data['user_id'] = $ulogin['user_id'];
            $save_data['ram_id'] = $ulogin['ram_id'];

            $save_data['sk'] = uuidCreate();
            $save_data['ctime'] = time();

            if ( !$model->insert($save_data) ) {
                throw new \Exception("保存失败");
            }

            // 更新成功 提交事务
            Db::commit();

            return apiResult('2000','提交成功',$save_data['uuid']);
        } catch (\Exception $e) {
            // 更新失败 回滚事务
            Db::rollback();
            return apiResult('5000',$e->getMessage());
        }
    }

    // 更新
    public function update(){
        $ulogin = $this->login_user;
        $param = file_get_contents('php://input');
        $param = json_decode($param,true);

        if ( empty($param['id']) ) {
            exception('id不能为空',400);
        }

        $fields = [
            'nomust'=>['name','description','status']
        ];
        $save_data = paramFilter($param,$fields);
        if (!empty($save_data['error_msg'])) {
            return apiResult('5000',$save_data['error_msg']);
        }
        if (empty($save_data)) {
            return apiResult('5000','无任何修改');
        }

        $model = new SkModel();
        // 启动事务 
        Db::startTrans();
        try{
            if ( $model->where('id',$param['id'])->update($save_data) === false ) {
                throw new \Exception("保存失败");
            }
            // 更新成功 提交事务
            Db::commit();

            return apiResult('2000','更新成功');
        } catch (\Exception $e) {
            // 更新失败 回滚事务
            Db::rollback();
            return apiResult('5000',$e->getMessage());
        }
    }

   


}
